package com.ics.cmsadmin.modules.pub.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ics.cmsadmin.frame.core.bean.ApiResponse;
import com.ics.cmsadmin.frame.core.enums.ApiResultEnum;
import com.ics.cmsadmin.frame.core.exception.CmsException;
import com.ics.cmsadmin.frame.core.bean.PageResult;
import com.ics.cmsadmin.modules.pub.bean.Unit;
import com.ics.cmsadmin.modules.pub.bean.UnitVO;
import com.ics.cmsadmin.modules.pub.service.UnitService;
import com.ics.cmsadmin.modules.sso.utils.SsoUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/units")
public class UnitsController extends ResourceController<UnitService, Unit, Integer> {
    @Resource
    private UnitService unitService;

    @GetMapping
    public ApiResponse unitsGet(String name, Integer subjectId, Integer courseId, Integer teacherId, Boolean isActive,
                                @RequestParam(value = "page", required = false) Integer page,
                                @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                HttpServletRequest request) {
        String userId = SsoUtils.getLoginUserId(request);
        Map<String, Object> param = new HashMap<>();
        param.put("name", name);
        param.put("subjectId", subjectId);
        param.put("courseId", courseId);
        param.put("teacherId", teacherId);
        param.put("isActive", isActive);
        param.put("page", page);
        param.put("pageSize", pageSize);
        if (page != null && pageSize != null) {
            PageHelper.startPage(page, pageSize);
        } else {
            List<UnitVO> data = unitService.getMultiple(param, userId);
            long total = data.size();
            return ApiResponse.getDefaultResponse(PageResult.getPage(total, data));
        }
        List<UnitVO> data = unitService.getMultiple(param, userId);
        long total = ((Page) data).getTotal();
        PageResult pageResult = PageResult.getPage(total, data);
        return ApiResponse.getDefaultResponse(pageResult);
    }

    @GetMapping("/{unitId}/detail")
    public ApiResponse get(@PathVariable Integer unitId,
                           HttpServletRequest request) {
        String userId = SsoUtils.getLoginUserId(request);
        return ApiResponse.getDefaultResponse(unitService.get(unitId, userId));
    }
}
